<template>
  <div v-loading="state.loading" :element-loading-background="state.elementLoadingBackground">
    <el-checkbox-group
        v-bind="$attrs"
        v-model="state.paramVal"
        @change="handleChange"
        :disabled="isValue($attrs.disabled) ? $attrs.disabled : state.formView"
    >
      <el-checkbox
          v-for="item in options"
          :value="item[valueKey]"
      >
        {{ item[labelKey] }}
      </el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  onMounted,
  reactive,
  watch,
  inject
} from 'vue'
import {isValue} from "@/utils/czr-util";
const emit = defineEmits(['emitParam', 'getObject'])
const props = defineProps({
  param: {},
  label: {},
  options: { type: Array, default: () => [] },
  labelKey: { type: String, default: 'label' },
  valueKey: { type: String, default: 'value' },
  static: {default: false}
})
const state = reactive({
  paramVal: props.param,
  loading: true,
  elementLoadingBackground: inject('element-loading-background', null),
  formView: inject('form-view', false),
})
watch(() => state.paramVal, (n) => {
  emit('emitParam', n)
})
watch(() => props.param, (n) => {
  state.paramVal = n
})
watch(() => [props.options, props.static], () => {
  state.loading = false
})
const optionsMapCpt = computed(() => {
  const map = new Map()
  props.options?.forEach((v: any) => {
    map.set(v[props.valueKey], v)
  })
  return map
})
const handleChange = (val: any) => {
  emit('getObject', val.map((v: any) => optionsMapCpt.value.get(v)))
}
onMounted(() => {
  if (props.static !== false || props.options?.length > 0) {
    state.loading = false
  }
})
</script>

<style scoped lang="scss">
</style>
